package com.cpsdna.module;

import com.cpsdna.bean.firm.Firm;
import com.cpsdna.bean.user.OperationLog;
import com.cpsdna.bean.user.User;
import com.cpsdna.util.SessionManger;
import eu.bitwalker.useragentutils.UserAgent;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.service.EntityService;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jianghao on 2017/2/27.
 */
@IocBean(fields = {"dao"})
@Ok("json:{locked:'password|salt', ignoreNull:true}")
@Fail("http:500")
@At("/firm")
public class FirmModule extends EntityService<Firm> {

    private static final Log log = Logs.get();


    @GET
    @At("/list")
    @Ok("beetl:/firm/list.btl")
    @Filters(@By(type = CheckSession.class, args = {User.USER_SESSION_KEY, "/login.htm?returnUrl=/firm/list.htm"}))
    public Map<String, Object> list() throws IOException {

        User user = SessionManger.getCurrentUser(Mvcs.getReq());
        if (!Strings.equals(user.getUserGroup(), "{1}"))
            Mvcs.getResp().sendRedirect("/error/403.htm");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user", user);
        List<Firm> firmList = dao().query(Firm.class, Cnd.where("firm_id", ">", 1));
        map.put("firmList", firmList);
        return map;
    }

    @Ok("raw")
    @At("/checkFirmName")
    public String checkMobile() {

        String firmName = Mvcs.getReq().getParameter("firmName").trim();

        if (Strings.isBlank(firmName))
            return "{\"data\":{\"error\":\"公司名称不能为空\"}}";
        else {
            Firm firm = dao().fetch(Firm.class, Cnd.where("firmName", "=", firmName));
            if (Lang.isEmpty(firm))
                return "{\"data\":{\"ok\":\"\"}}";
            else
                return "{\"data\":{\"error\":\"公司名称已存在\"}}";
        }
    }

    @GET
    @At("/add")
    @Ok("beetl:/firm/add.btl")
    @Filters(@By(type = CheckSession.class, args = {User.USER_SESSION_KEY, "/login.htm?returnUrl=/firm/add.htm"}))
    public Map<String, Object> add() throws IOException {

        User user = SessionManger.getCurrentUser(Mvcs.getReq());
        if (!Strings.equals(user.getUserGroup(), "{1}"))
            Mvcs.getResp().sendRedirect("/error/403.htm");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user", user);
        return map;
    }

    @POST
    @At("/add")
    @Ok("redirect:${obj}")
    @Filters(@By(type = CheckSession.class, args = {User.USER_SESSION_KEY, "/login.htm?returnUrl=/firm/add.htm"}))
    public String add(@Param("firmShortName") String firmShortName, @Param("firmName") String firmName) {

        User user = SessionManger.getCurrentUser(Mvcs.getReq());
        if (!Strings.equals(user.getUserGroup(), "{1}"))
            return "/error/403.html";

        Firm firm = dao().fetch(Firm.class, Cnd.where("firmName", "=", Strings.isNotBlank(firmName) ? firmName : "0"));
        if (Strings.isNotBlank(firmShortName) && Lang.isEmpty(firm)) {

            try {

                firm = new Firm();
                firm.setFirmName(firmName);
                firm.setFirmShortName(firmShortName);
                dao().insert(firm);
                UserAgent userAgent = UserAgent.parseUserAgentString(Mvcs.getReq().getHeader("User-Agent"));
                OperationLog operationLog = new OperationLog(user.getUserId(),
                        "新增公司" + firm.getFirmId(), Lang.getIP
                        (Mvcs.getReq
                                ()),
                        "操作系统版本（"
                                + userAgent
                                .getOperatingSystem() + "）；浏览器版本（" + userAgent.getBrowser() + "-" + userAgent
                                .getBrowserVersion() + "）", Times.now());
                dao().insert(operationLog);
                return "/firm/add.htm?alert=success";
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return "/firm/add.htm?alert=error";
            }
        }
        return "/firm/add.htm?alert=error";
    }
}